package com.lifeng.security;

import com.lifeng.bean.User;
import com.lifeng.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lifeng on 2019/8/9.
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(CustomUserDetailsService.class);
    @Resource
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //查询系统用户
        User user = userService.selectByUserName(userName);
        if(user == null) {
            log.error(userName+":账号不存在");
            throw new UsernameNotFoundException("账号不存在");
        }
        //查询该用户的所有权限
        List<String> permissionList = userService.selectPermissionByUserId(user.getId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for(String permission:permissionList){
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission);
            grantedAuthorities.add(grantedAuthority);
        }
        MySecurityUser mySecurityUser = new MySecurityUser(user,user.getUserName(),user.getPassWord(),grantedAuthorities);
        return mySecurityUser;
    }
}
